import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message, Tabs, Tag, Select } from 'antd';
import { CheckOutlined, CloseOutlined, EyeOutlined } from '@ant-design/icons';
import { TaskApi, TaskVO } from '../../../api/bpm/task';

const { TabPane } = Tabs;
const { TextArea } = Input;
const { Option } = Select;

const BPMTask: React.FC = () => {
  const [todoTasks, setTodoTasks] = useState<TaskVO[]>([]);
  const [doneTasks, setDoneTasks] = useState<TaskVO[]>([]);
  const [managerTasks, setManagerTasks] = useState<TaskVO[]>([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('todo');
  const [approvalModalVisible, setApprovalModalVisible] = useState(false);
  const [currentTask, setCurrentTask] = useState<TaskVO | null>(null);
  const [form] = Form.useForm();

  // 获取待办任务
  const fetchTodoTasks = async () => {
    setLoading(true);
    try {
      const response = await TaskApi.getTaskTodoPage({});
      setTodoTasks(response.data?.list || []);
    } catch (error) {
      message.error('获取待办任务失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取已办任务
  const fetchDoneTasks = async () => {
    setLoading(true);
    try {
      const response = await TaskApi.getTaskDonePage({});
      setDoneTasks(response.data?.list || []);
    } catch (error) {
      message.error('获取已办任务失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取管理任务
  const fetchManagerTasks = async () => {
    setLoading(true);
    try {
      const response = await TaskApi.getTaskManagerPage({});
      setManagerTasks(response.data?.list || []);
    } catch (error) {
      message.error('获取管理任务失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (activeTab === 'todo') {
      fetchTodoTasks();
    } else if (activeTab === 'done') {
      fetchDoneTasks();
    } else if (activeTab === 'manager') {
      fetchManagerTasks();
    }
  }, [activeTab]);

  // 审批任务
  const handleApproval = async (values: any) => {
    if (!currentTask) return;
    
    try {
      if (values.result === 2) {
        await TaskApi.approveTask({
          id: currentTask.id,
          comment: values.reason,
          approve: true
        });
      } else {
        await TaskApi.rejectTask({
          id: currentTask.id,
          comment: values.reason,
          approve: false
        });
      }
      message.success('审批成功');
      setApprovalModalVisible(false);
      setCurrentTask(null);
      form.resetFields();
      fetchTodoTasks();
    } catch (error) {
      message.error('审批失败');
    }
  };

  // 打开审批模态框
  const openApprovalModal = (task: TaskVO) => {
    setCurrentTask(task);
    setApprovalModalVisible(true);
  };

  const todoColumns = [
    {
      title: '任务名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '流程名称',
      dataIndex: 'processInstanceName',
      key: 'processInstanceName',
    },
    {
      title: '发起人',
      dataIndex: 'startUserNickname',
      key: 'startUserNickname',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: TaskVO) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<CheckOutlined />}
            onClick={() => openApprovalModal(record)}
          >
            审批
          </Button>
          <Button
            type="default"
            icon={<EyeOutlined />}
          >
            查看
          </Button>
        </Space>
      ),
    },
  ];

  const doneColumns = [
    {
      title: '任务名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '流程名称',
      dataIndex: 'processInstanceName',
      key: 'processInstanceName',
    },
    {
      title: '发起人',
      dataIndex: 'startUserNickname',
      key: 'startUserNickname',
    },
    {
      title: '审批结果',
      dataIndex: 'result',
      key: 'result',
      render: (result: number) => (
        <Tag color={result === 2 ? 'green' : result === 3 ? 'red' : 'orange'}>
          {result === 2 ? '通过' : result === 3 ? '拒绝' : '处理中'}
        </Tag>
      ),
    },
    {
      title: '完成时间',
      dataIndex: 'endTime',
      key: 'endTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: TaskVO) => (
        <Button
          type="default"
          icon={<EyeOutlined />}
        >
          查看
        </Button>
      ),
    },
  ];

  const getCurrentData = () => {
    switch (activeTab) {
      case 'todo':
        return todoTasks;
      case 'done':
        return doneTasks;
      case 'manager':
        return managerTasks;
      default:
        return [];
    }
  };

  const getCurrentColumns = () => {
    switch (activeTab) {
      case 'todo':
        return todoColumns;
      case 'done':
      case 'manager':
        return doneColumns;
      default:
        return todoColumns;
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="待办任务" key="todo" />
        <TabPane tab="已办任务" key="done" />
        <TabPane tab="管理任务" key="manager" />
      </Tabs>

      <Table
        columns={getCurrentColumns()}
        dataSource={getCurrentData()}
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      <Modal
        title="任务审批"
        open={approvalModalVisible}
        onCancel={() => {
          setApprovalModalVisible(false);
          setCurrentTask(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleApproval}
        >
          <Form.Item
            name="result"
            label="审批结果"
            rules={[{ required: true, message: '请选择审批结果' }]}
          >
            <Select placeholder="请选择审批结果">
              <Option value={2}>通过</Option>
              <Option value={3}>拒绝</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="reason"
            label="审批意见"
            rules={[{ required: true, message: '请输入审批意见' }]}
          >
            <TextArea placeholder="请输入审批意见" rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BPMTask;